﻿using System.Configuration;
using System.Data;
using System.Windows;
using CommunityToolkit.Mvvm.Messaging;
using HostWpfApp.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;

namespace HostWpfApp;

//WPF应用程序默认有个隐式Main函数，需要将App.xaml的属性修改为Page才能显示定义Main函数 
public partial class App : Application
{
    [STAThread]
    static void Main(string[] args)
    {
        // using IHost host = Host.CreateDefaultBuilder(args).Build();
        // 这里只是把build放到方法里面了
        using IHost host = CreateHostBuilder(args).Build();
        //start无阻塞，后续代码正常执行，run阻塞
        host.Start();
        var app = new App();
        app.InitializeComponent();
        //将窗口赋值给WPF程序的MainWindow属性
        app.MainWindow = host.Services.GetRequiredService<MainWindow>();
        app.MainWindow.Show();
        app.Run();
    }

    private static IHostBuilder CreateHostBuilder(string[] args)
    {
        return Host.CreateDefaultBuilder(args)
            .ConfigureServices(container =>
            {
                container.AddSingleton<MainWindow>(sp => new MainWindow()
                {
                    DataContext = sp.GetRequiredService<MainViewModel>()
                });
                container.AddSingleton<MainViewModel>();
                // 后台服务实现BackgroundService，使用AddHostedService注册后host会自动获取并运行
                container.AddHostedService<CheckUpdateService>();
                // 注入Message
                container.AddSingleton<WeakReferenceMessenger>();
                container.AddSingleton<IMessenger, WeakReferenceMessenger>(provider =>
                    provider.GetRequiredService<WeakReferenceMessenger>());
                // 注册dispatcher(保证在主线程执行代码)
                container.AddSingleton(_ => Current.Dispatcher);
                // 还可以注入MessageBoxService、OpenfileService...
            })
            .ConfigureLogging(logging =>
            {
                //先清除微软自带的log包，再使用serilog包
                //注意：其他的任何任意地方都需要变
                //rollingInterval每天生成一个带日期后缀的日志文件
                logging.ClearProviders();
                Log.Logger = new LoggerConfiguration()
                    .WriteTo.File("log_hostwpf.txt", rollingInterval: RollingInterval.Day)
                    .CreateLogger();
                logging.AddSerilog(Log.Logger);
            });
    }
}